package com.ellecity06.cwhiskymall.ui.mine.auth

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.aesDecode
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.common.utils.ImageUploadUtils
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.constant.Constants
import com.ellecity06.cwhiskymall.http.request
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/12/3 18:13
 * @des
 */
class AuthNameViewModel : BaseMviViewModel<AuthNameState, AuthNameIntent>() {
    /**
     * 正面身份证照片
     */
    private var facePath: String? = null

    /**
     * 反面照片
     */
    private var backPath: String? = null
    override suspend fun collectIntent(it: AuthNameIntent) {
        when (it) {
            is AuthNameIntent.UploadImage -> {
                uploadImage(it.path, it.isFace)
            }

            is AuthNameIntent.Submit -> submitAuth(it)
        }
    }

    private fun submitAuth(it: AuthNameIntent.Submit) {
        if (facePath == null) {
            ToastUtils.show("请选择身份证正面照片")
            return
        }
        if (backPath == null) {
            ToastUtils.show("请选择身份证反面照片")
            return
        }
        if (it.userName == null) {
            ToastUtils.show("姓名为空，请先选择身份照片进行识别")
            return
        }
        if (it.identifyNum == null) {
            ToastUtils.show("身份证号为空，请先选择身份照片进行识别")
            return
        }
        logD("正面=$facePath")
        logD("反面=$backPath")
        request(api = { submitAuth( backPath!!,facePath!!, it.identifyNum, it.userName) }, showLoading = true, success = {
            mState.postEvent(AuthNameState.SubmitSuccess)
        })
    }

    private fun uploadImage(path: String, face: Boolean) {

        // 上传图片，如果是正面图片传成功之后就传给后台识别身份证号码
        request(api = { ossSts() }, success = {
            ImageUploadUtils.upload(
                it?.endpoint ?: "",
                it?.bucket ?: "",
                (it?.AccessKeyId ?: "").aesDecode(Constants.AES_KEY),
                it?.AccessKeySecret ?: "",
                it?.SecurityToken ?: "",
                path,
                onFail = {
                    uploadError(face)
                }
            ) { imageUrl ->
                if (face) {
                    facePath = imageUrl
                    // 提交接口识别身份证
                    request(api = { recognizeIdCard(imageUrl) },showLoading = true, success = {
                        // 因为只识别正面照片，所以也只需要正面的数据
                        if (it?.frontResult != null) {
                            mState.postEvent(AuthNameState.UpdateSuccess(it.frontResult))
                        } else {
                            uploadError(face)
                        }
                    }, error = {
                        uploadError(face)
                    })
                } else {
                    backPath = imageUrl
                }

            }
        }, error = {
            uploadError(face)
        })

    }

    private fun uploadError(isFace: Boolean) {
        dismissLoading()
        viewModelScope.launch {
            mState.postEvent(AuthNameState.UpdateFail(isFace))
        }
    }
}